package android.medicalcloud.com.yiapp.base.net;

import android.medicalcloud.com.yiapp.base.utils.Logger;
import android.medicalcloud.com.yiapp.base.utils.StringTools;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

public class HttpUrlConnectionRequest {


    protected static String get(String urlStr,Map <String,String> header) {
        HttpURLConnection conn = null;
        try {


            URL url = new URL(urlStr); //创建URL对象
            //返回一个URLConnection对象，它表示到URL所引用的远程对象的连接
            conn = (HttpURLConnection) url.openConnection();
            setHeader(conn, header);
            conn.setConnectTimeout(10000); //设置连接超时为10秒
            conn.setRequestMethod("GET"); //设定请求方式
            conn.connect(); //建立到远程对象的实际连接
            //返回打开连接读取的输入流
            DataInputStream dis = new DataInputStream(conn.getInputStream());
//            conn.setRequestProperty("Cookie", "Set-Cookie: JSESSIONID=0E5104C9E195D677C06671562983A3A2; Path=/; HttpOnly");
            //判断是否正常响应数据
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("网络错误异常！!!!");
                return input2Str( conn.getErrorStream());
            }
            String reslut= input2Str(dis);
            if (StringTools.isNullOrEmpty(reslut)){
                reslut="{}";
            }


            return reslut;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("这是异常！");
        } finally {
            if (conn != null) {
                conn.disconnect(); //中断连接
            }
        }
        return "";
    }


    static String input2Str(InputStream is) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i;
            while ((i = is.read()) != -1) {
                baos.write(i);
            }
            String str = baos.toString();
            System.out.println(str);
            return str;

        }catch (Exception e){
            Logger.e(e.getLocalizedMessage(),e);
        }
        return "";
    }


    static  void setHeader(HttpURLConnection conn,Map <String,String> header){
        if (header==null){
            return;
        }

        Iterator iter = header.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = entry.getKey().toString();
            String val = entry.getValue().toString();
//            Logger.e("header=="+key+" "+val);

            conn.setRequestProperty(key, val);
        }
        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    }


    public static String post(String actionUrl, Map<String, String> headParams,
                              Map<String, Object> params){

        String paramsStr = postParam(params);
        Logger.e("post param "+paramsStr);
        URL url;
        try {
            url = new URL(actionUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();

            if(headParams!=null){
                for(String key : headParams.keySet()){
                    Logger.e("header=="+key+" "+headParams.get(key));
                    conn.setRequestProperty(key, headParams.get(key));
                }
            }
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(1000 * 5);
            conn.getOutputStream().write(paramsStr.getBytes("utf-8"));
            conn.getOutputStream().flush();
            conn.getOutputStream().close();

            int httpCode = conn.getResponseCode();
            Logger.e("httpCode = "+httpCode);

            if (httpCode == 200) {
                InputStream in = conn.getInputStream();
                String reslut = input2Str(in);
                System.out.println("sb:"+reslut);
                in.close();
                return reslut;
            }else{
                InputStream in = conn.getErrorStream();
                String reslut = input2Str(in);
                System.out.println("sb:"+reslut);
                in.close();
                return reslut;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private  static String postParam(Map<String, Object> params){
        JSONObject jsonObject = new JSONObject(params);
        JSONObject jsRequest = new JSONObject();
        try {
            jsRequest.put("data",jsonObject);
            return  jsRequest.toString();
        }catch (Exception e){
            return "";
        }
    }


}